'''
Created on Mar 23, 2011

@author: Mario
'''


from Bio import ExPASy
from Bio import SwissProt
import urllib2, re;

def fetch(id):
    handle = ExPASy.get_sprot_raw(id)
    record = SwissProt.read(handle)
    return record.sequence
####

def fetch_uniparc (id):
    url = 'http://www.uniprot.org/uniparc/?query=' + id + '&sort=score'

    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.read() 
    
    p = re.compile ('.*\<strong\>0\</strong\> result for .*');
    if len(re.findall(p,the_page)) != 0:
        return '';
    # to znaci da ga nema u uniprot bazi uopce
    
    p = re.compile ('\<strong\>0\</strong\> result for ');
    print re.findall(p,the_page);
    
    
    p = re.compile('addOrAppendCart\(\'(.*?)\'\)')
    target_id = re.findall(p, the_page)
    
        
    
    print target_id[0]
    
    url = 'http://www.uniprot.org/uniparc/' + target_id[0]    + '.fasta'               # postoji lista membera clustera koja krece sa Q9QY76
    
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.readlines()
    seq = "";
    for line in the_page:
        if re.match(">.*", line):
            continue;
        seq = seq + line.rstrip();
    
    return seq
    
    
from Bio.Align.Applications import ClustalwCommandline

def score(p1_str, p2_str, tmp_file, clustal_exe):
    f = open(tmp_file,'w')
    f.write('>P1\n')
    f.write(p1_str + '\n')
    f.write('>P2\n')
    f.write(p2_str + '\n')
    f.close()
    
    cline = ClustalwCommandline (clustal_exe, infile = tmp_file, score="percent");
    output = cline()[0]

    #Vraca prvi rezultat sequence comparisona u %
    str1 = re.findall(r'Score:\s*\d+', output)[0]
    num = int(re.findall(r'\d+', str1)[0])
    return num
####

"""
def create_fasta(graph, file):
    vs = graph.vs;
    i = 0;
    for v in vs :
        try:
            print v['uniprot'];
            prot2file(fetch(v['uniprot']), v['refseq'], i, file)
            i += 1;
        except ValueError:
            try:
                print v['uniprot'], " X";
                #desc = re.split(" ", v['dip_id'], 1000)
                prot2file(fetch(descriptive_id(v['refseq'])), v['refseq'], i, file)
                i += 1;
            except UnboundLocalError:
                print v['uniprot'], " X OBSOLETE";
                prot2file('', v['refseq'] + ' OBSOLETE', -1, file)
                #i += 1;
    return
"""

def create_fasta(graph, file):
    vs = graph.vs;
    i = 0;
    for v in vs :
        try:
            un = 'uniprot';
            dip  = 'dip_id';
            print v[un];
            prot2file(fetch(v[un]), v[dip], i, file)
            i += 1;
        except ValueError:
            try:
                print v[un], " X";
                desc = re.split(" ", v[dip], 1000)
                prot2file(fetch(descriptive_id(desc[len(desc)-1])), v[dip], i, file)
                i += 1;
            except UnboundLocalError:
                print v[un], " X OBSOLETE";
                print v['refseq']
                seq = fetch_uniparc(v['refseq']);
                if seq == '':
                    continue; # onda se ne zapisuje u fasta file
                prot2file(seq, v['refseq'],  i, file)
                i += 1;
    return
####

def prot2file(prot, desc, pid, file):
    f = open(file, 'a');
    f.write('>P' + str(pid) + '     ' + desc + '\n');
    f.write(prot + '\n');
    f.close();
    return
####

import urllib

def descriptive_id(desc):
    handle = ExPASy.sprot_search_ful(desc)      #"heat shock protein 90 10116"
    result = handle.read()

    p = re.compile('(http.*score)\n', re.DOTALL)
    if "Status: 302" in result:
        url = re.findall(p, result)
        url = re.sub(' ', '%20', url[0])

    sock = urllib.urlopen(url)
    htmlSource = sock.read()
    sock.close()

    #ako ima addOrAppendCart, onda je nasao barem jedan rezultat
    p = re.compile('"addOrAppendCart\(\'([\w]{6})')
    if "addOrAppendCart" in htmlSource:
        target_id = re.findall(p, htmlSource)
    
    return target_id[0]          #trazeni rezultat
####

def evaluate_fastas(file1, file2, result_file, tmp_fasta, clustal_exe):
#f1 = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/Celeg20101010.faa', 'r');
#f2 = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/Hpylo20101010.faa', 'r');
    
    f1 = open(file1, 'r');
    f2 = open(file2, 'r');
    
    s1 = f1.readlines()
    s2 = f2.readlines()
    
    print s1
    
    result = [];
    
    
    offset1 = 0; i = 0;
    while (i < (len(s1)/2)):
        if float(re.findall(">P(-*\d+) ", s1[2*i])[0]) == (-1):
            offset1 += 1;
            i+=1
        else :
            #print i-offset, s1[2*i +1]
            row = [];
            offset2 = 0; j = 0;
            while (j < (len(s2)/2)):
                if float(re.findall(">P(-*\d+) ", s2[2*j])[0]) == (-1):
                    offset2 += 1;
                    j+=1
                else:
                    #print j-offset2, s2[2*j +1]
                    row.append(score( s1[2*i +1], s2[2*j +1], tmp_fasta, clustal_exe))
                    j += 1;
            result.append(row);
            print result;
            i += 1;
    
    f = open(result_file, 'w');
    for res in result:
        f.write(str(res) + "\n");
####

def read_results(filename):
    #f = open('/Users/Mario/Documents/workspaceCPP/BIO_Projekt/working_data/result.txt', 'r');
    f = open(filename, 'r');

    matrix = []
    for line in f.readlines():
        line = line.lstrip('[')
        line = line.rstrip(']\n')
        line = line.split(', ')
        row = []
        for element in line:
            row.append(int(element))
        matrix.append(row)
    return matrix
####

    
def parseConfigFile ():
    i = 0;
    config_file = r"../../config/cmp_config.txt";
    file = open (config_file, "r");
    lines = file.readlines();
    for line in lines:
        if re.match("^#", line):
            print 'comment'
            continue;           #to je komentar
        elif len(line) <= 1:    #avoid the line feed
            print 'line feed'
            continue;
        else:
            line = line.strip();
            if i == 0:
                tmp_dir = line + '\\';
                print tmp_dir 
                i=+1;
            elif i == 1:
                tmp_fasta = tmp_dir + line; 
                print tmp_fasta
                i+=1;
            elif i == 2:
                tmp_result = tmp_dir + line;
                print tmp_result
                i+=1;
            elif i == 3:
                gml_dir = line + '\\';
                print gml_dir
                i+=1;
            else:
                (first_gml, sec_gml) = line.split(' ');
                print first_gml, sec_gml;
                
    return (tmp_dir, tmp_fasta, tmp_result, gml_dir, first_gml, sec_gml);

def parseClustalConfig ():
    config_file = r"../../config/clustal_config.txt";
    file = open (config_file, "r");
    lines = file.readlines();
    for line in lines:
        if re.match("^#", line):
            continue;
        elif len(line) <= 1:    #avoid the line feed
            continue;
        else:
            clustal_exe = line;
    
    return clustal_exe